package com.hai.qtalk;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.hai.util.HttpUtil;


public class ChatActivity extends Activity {

	ImageView image;
	TextView who;
	EditText input;//输入文本框
	TextView show;//聊天消息显示框
	Button send;//发送按钮
	public static Handler handler;//
	private String split="y9t";
	String toUID;
	String toUname;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			setContentView(R.layout.chat);
			
			Intent intent = getIntent();
			Bundle bundle = intent.getExtras();
			String name = bundle.getString("name");
			
		image = (ImageView)findViewById(R.id.image);
		who = (TextView)findViewById(R.id.who);
		input = (EditText)findViewById(R.id.input);
		send = (Button)findViewById(R.id.send);
		show = (TextView)findViewById(R.id.show);
		
		who.setText(name);
		
		String[] temp=((String) who.getText()).split("\\(",0);
		toUname=temp[0];
		String temp2=temp[temp.length-1];
		//System.out.println(temp2+"000000");
	    toUID=temp2.substring(0, temp2.length()-1);
		
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg){
				//如果消息来自子线程
				try {
					if(msg.what==0x123){
						//将读取的内容追加显示在文本框中
						show.append("\n"+msg.obj.toString());
					}
				} catch (Exception e) {
					System.out.println("追加文本到聊天窗口异常");
					e.printStackTrace();
				}
			}
		};
		
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					//当用户按下发送按钮后，将用户输入的数据封装成Message
					//然后发送给子线程的Handler

					
					String inputString=input.getText().toString();
					
					Message msg=new Message();
					msg.what=0x345;
					msg.obj=toUID+split+inputString;//
					FragmentTabs.clientThread.receiveHandler.handleMessage(msg);
					//将发送的内容追加显示在文本框中
					show.append("\n"+HttpUtil.UNAME+": "+inputString);
					//清空input文本框
					input.setText("");
				} catch (Exception e) {
					System.out.println("点击发送后报错");
					e.printStackTrace();
				}
				
			}
		});
	}
	
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		 
//        if (keyCode == KeyEvent.KEYCODE_BACK
//                 && event.getRepeatCount() == 0) {
//            //do something...
//             return true;
//         }
//         return super.onKeyDown(keyCode, event);
//     }
	
}
